package com.cabinet;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: denny
 * Date: 8/20/13
 * Time: 5:29 PM
 * To change this template use File | Settings | File Templates.
 */
public class Config {
  static Properties props = new Properties();
  static final String FILE_NAME = "config.txt";
  static Map<String,Image> imgCache = new HashMap<>();
  static Map<String,CodesBlock> codesBlocks = new HashMap<>();

  static{
    try{
      props.load(new FileInputStream(FILE_NAME));
      for( String s : props.stringPropertyNames() ){
        System.out.println(FILE_NAME+"  "+s+"="+props.get(s));
      }
    }catch (Exception e){
      System.err.println("no config file: "+FILE_NAME);
      System.err.flush();
      System.exit(1);
    }

    final String FILE_CODES = "codes.txt";
    try{
      loadCodesBlocks(FILE_CODES);
    }catch (Exception e){
      e.printStackTrace();
      throw new RuntimeException(FILE_CODES, e);
//      System.out.flush();
//      System.err.flush();
//      System.exit(1);
    }
  }

  static void loadCodesBlocks(String file) throws Exception{
    System.out.println("reading "+file);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    CodesBlock codesBlock=null;
   // HashSet<String> allCodes = new HashSet<>();
    while( (line=br.readLine()) != null ){
      line = line.trim();
      if( line.length()>0 && !line.startsWith("#") ){
        if( line.startsWith("BLOCK") ){
          if( codesBlock!=null ){
            codesBlock.readFinish();
          }
          codesBlock = new CodesBlock();
          codesBlocks.put(line, codesBlock);
        }else{
//          if( ! allCodes.add(line) ){
//            throw new IllegalStateException("error in "+file+" duplicate code "+line);
//          }
          if( codesBlock==null ){
            throw new IllegalStateException("error in "+file+" code before block "+line);
          }
          codesBlock.addCode(line);
        }
      }
    }
    if( codesBlock!=null ){
      codesBlock.readFinish();
    }
    for( CodesBlockName cb : CodesBlockName.values() ){
      if( !codesBlocks.containsKey(cb.name()) ){
        throw new IllegalStateException("error in "+file+" no "+cb);
      }
    }
    if( CodesBlockName.values().length!=codesBlocks.size() ){
      throw new IllegalStateException("error in "+file+" extra block");
    }

  }

  static String str(String name){
    return props.getProperty(name);
  }

  static int getInt(String name){
    return Integer.parseInt(str(name).trim());
  }

  static boolean getBool(String name){
    return "true".equals(str(name));
  }

  public static Set<Integer> getVisibleStudents(){
    String v = str("visible.students");
    StringTokenizer st = new StringTokenizer(v,", ");
    Set<Integer> set = new HashSet<>();
    while(st.hasMoreElements()){
      set.add(Integer.parseInt(st.nextToken()));
    }
    return set;
  }

  public static Set<Integer> getVisibleAudio(){
    String v = str("visible.audio");
    StringTokenizer st = new StringTokenizer(v,", ");
    Set<Integer> set = new HashSet<>();
    while(st.hasMoreElements()){
      set.add(Integer.parseInt(st.nextToken()));
    }
    return set;
  }

  public static File classesDB(){
    File dataDir = dataDir();
    return new File(dataDir,"classesDB.xml");
  }

  public static File locationsDB(){
    File dataDir = dataDir();
    return new File(dataDir,"locationsDB.xml");
  }

  private static File dataDir() {
    File dataDir = new File(new File("."), "data");
    dataDir.mkdir();
    return dataDir;
  }

  public static File imageDir() {
    File dir = new File(new File("."), "image");
    return dir;
  }
  
  public static BufferedImage getImage(String fileName){
    try {
      return ImageIO.read(new File(imageDir(), fileName));
    } catch (IOException e) {
      throw new RuntimeException("fileName="+fileName, e);
    }
  }

  public static Image getScaledImage(String fileName, int w, int h){
      String key = fileName+" "+w+" "+h;
      if( imgCache.get(key)==null ){
          BufferedImage orig = getImage(fileName);
          if( w==0 ){
              w = orig.getWidth() * h / orig.getHeight();
          }
          if( h==0 ){
              h = orig.getHeight() * w / orig.getWidth();
          }
          Image dimg = orig.getScaledInstance(w, h, Image.SCALE_SMOOTH);
        imgCache.put(key, dimg);
      }
      return imgCache.get(key);
  }

  public static File classesDBBackup(){
    File dataDir = dataDir();
    return new File(dataDir,"classesDB.xml.bak."+System.currentTimeMillis());
  }

  public static boolean left(MouseEvent e){
    return SwingUtilities.isLeftMouseButton(e);
  }

  public static boolean right(MouseEvent e){
    return SwingUtilities.isRightMouseButton(e);
  }

  public static boolean debugPortWindow(){
    return getBool("debugPortWindow");

  }
}
